<template>
  <el-dialog v-model="editDialogFormVisible" title="编辑用户" width="500">
    <el-form :model="editForm">
      <el-form-item label="角色昵称" :label-width="formLabelWidth">
        <el-input v-model="editForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色标识" :label-width="formLabelWidth">
        <el-input v-model="editForm.flag" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button @click="addClick">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, toRefs } from "vue";
import { ElMessage } from "element-plus";
import http from "../../../../util/http.js";
import { defineProps } from "vue";

const props = defineProps({
  editFormVisible: Boolean,
  editFormData: Object, // 接收从父组件传递的行数据
});

const emit = defineEmits(["update:editFormVisible", "refreshTable"]);

const editDialogFormVisible = ref(props.editFormVisible);
const formLabelWidth = "140px";

const editForm = reactive({
  name: "",
  flag: "",
});

watch(
  () => props.editFormData,
  (newVal) => {
    if (newVal) {
      Object.assign(editForm, newVal); // 更新表单数据
    }
  },
  { immediate: true }
);

watch(
  () => props.editFormVisible,
  (newVal) => {
    editDialogFormVisible.value = newVal;
    if (!newVal) {
      Object.assign(editForm, { name: "", flag: "" }); // 清空表单数据
    }
  }
);

const closeDialog = () => {
  editDialogFormVisible.value = false;
  emit("update:editFormVisible", false);
};

const addClick = () => {
  http.post("/roles/editrole", editForm).then((res) => {
    if (editForm.name && editForm.flag) {
      editDialogFormVisible.value = false;
      ElMessage.success("修改成功");
      closeDialog();
      emit("refreshTable");
    } else {
      ElMessage.error("请填写完整信息");
    }
  });
};
</script>

<style scoped>
</style>
